<?php
namespace Modules\Skinov\Controllers;

use Modules\Skinov\Services\UserWechatService;

class CallbackController extends ControllerBase {
  private function __redirectFrontend($target_url) {
    return $this -> response -> redirect($this -> config -> WECHAT_FRONTEND_URL.'/'.$target_url, true, 200);
  }

  private function getWeChatUser() {
    if(APPLICATION_ENV === 'development') {
      return new \Overtrue\Socialite\User(['id'=>$this -> config -> OPENID]);
    } else {
      return $this -> easyWeChat -> oauth -> scopes(['snsapi_base', 'snsapi_userinfo']) -> user();
    }
  }

  public function redirectFrontendAction() {
    //$this -> session -> destroy(true);
    //if(!$this -> session -> has('user')) {
      $user = $this -> getWeChatUser();
      $resUserWallet = (new UserWechatService()) -> findFirstByOpenidHasPid($user -> getId());
      if($resUserWallet['code'] !== 0) {
        return $this -> _returnScript('用户信息获取失败!', $this -> config -> WECHAT_FRONTEND_URL.'/error?msg='.'用户信息获取失败');
      } else {
        //$token = \Components\User\Sha\Auth::encryptToken(['user'=> ['id' => $resUserWallet['model'] -> id]]);
        //$this -> session -> remove('user');
        $this -> session -> set('user', ['id' => $resUserWallet['model'] -> id]);
      }
    //}

    return $this -> __redirectFrontend($this -> request -> getQuery('target_url', 'string', 'shop', true));
  }

  public function redirectRecommendAction() {
    $user = $this -> getWeChatUser();
    $data = [];
    $data['user_wallet'] = $user -> getOriginal();
    $resUserWallet = (new UserWechatService()) -> findFirstByOpenidHasPid($user -> getId(), $data, $this -> request -> get('pid', 'int', 0, true));
    if($resUserWallet['code'] !== 0) {
      return $this -> _returnScript('用户信息获取失败!', $this -> config -> WECHAT_FRONTEND_URL.'/error?msg='.'用户信息获取失败');
    } else {
      $this -> session -> set('user', ['id' => $resUserWallet['model'] -> id]);
    }

    return $this -> __redirectFrontend($this -> request -> getQuery('target_url', 'string', 'shop', true));
  }
}
